package com.lib.common.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import androidx.viewpager.widget.ViewPager;

/**
 * @author 一叶丶枫凌
 * Created on 2017-05-17 9:34
 */
public class AdViewPager extends ViewPager {

    private float mXOrigin;
    private float mYOrigin;
    private boolean mHasMove;
    private int mRealViewPagerCount;
    private IndicatorView mIndicatorView;
    private OnPagerClickListener mOnPagerClickListener;

    public interface OnPagerClickListener {

        void onPagerClicked(View v, int position);
    }

    public void setOnPagerClickListener(OnPagerClickListener l) {

        mOnPagerClickListener = l;
    }

    public AdViewPager(Context context) {

        this(context, null);
    }

    public AdViewPager(Context context, AttributeSet attrs) {

        super(context, attrs);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        super.onTouchEvent(event);
        int action = event.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                if (mIndicatorView != null) {
                    mIndicatorView.setAutoScroll(false);
                }
                mXOrigin = event.getX();
                mYOrigin = event.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                if (Math.abs(event.getX() - mXOrigin) > 10 || Math.abs(event.getY() - mYOrigin) > 10) {
                    mHasMove = true;
                }
                break;
            case MotionEvent.ACTION_UP:
                if (!mHasMove && mOnPagerClickListener != null) {
                    if (mRealViewPagerCount == 0) {
                        mOnPagerClickListener.onPagerClicked(this, getCurrentItem());
                    } else {
                        mOnPagerClickListener.onPagerClicked(this, getCurrentItem() % mRealViewPagerCount);
                    }
                }
                mHasMove = false;
                if (mIndicatorView != null) {
                    mIndicatorView.setAutoScroll(true);
                }
                break;
        }
        return true;
    }

    public void setIndicatorView(IndicatorView indicatorView, int realViewPagerCount) {
        mIndicatorView = indicatorView;
        mRealViewPagerCount = realViewPagerCount;
        mIndicatorView.setViewPager(this, realViewPagerCount);
    }
}